<template>
  <div class="app-container">
    <my-affix :offset="0" style="background: #fff;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="箱子id" prop="id">
          <el-input v-model="queryParams.id" placeholder="请输入箱子id" clearable />
        </el-form-item>
        <el-form-item label="盒子名称" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入盒子名称" clearable
                    />
        </el-form-item>
        <el-form-item label="盒子状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择盒子状态">
            <el-option v-for="dict in dict.type.box_status" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盒子类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择盒子类型">
            <el-option v-for="dict in dict.type.box_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['system:wxs_box:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                     v-hasPermi="['system:wxs_box:edit']">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-hasPermi="['system:wxs_box:remove']">删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['system:wxs_box:export']">导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </my-affix>
    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="箱子ID" align="center" prop="id"/>
      <el-table-column label="盒子名称" align="center" prop="title"/>
      <el-table-column label="盒子分类" align="center" prop="categoryName"/>
      <el-table-column label="盒子封面图" align="center" prop="imgurl" width="180">
        <template slot-scope="scope">
          <el-image fit="cover" :src="scope.row.imgurl" style="width: 150px; height: 80px"/>
        </template>
      </el-table-column>
      <el-table-column label="排序值" align="center" prop="sort"/>
      <el-table-column label="盒子状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">上架</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 2">下架</el-tag>
          <el-tag type="warning" v-if="scope.row.status == 3">售罄</el-tag>
          <el-tag type="warning" v-if="scope.row.status == 4">删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="盒子价格" align="center" prop="price"/>
      <el-table-column label="是否显示" sortable="custom" align="center" prop="ifPublicShow">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.ifPublicShow == 0">充值可见</el-tag>
          <el-tag type="warning" v-if="scope.row.ifPublicShow == 1">登录可见</el-tag>
          <el-tag type="danger" v-if="scope.row.ifPublicShow == 2">公开可见</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阶段赏" align="center" prop="goodsInterval"/>
      <el-table-column label="抽成" align="center" prop="discount"/>
      <el-table-column label="盈利" align="center" prop="profit"/>
      <el-table-column label="奖池现有奖金" align="center" prop="menKan"/>
      <el-table-column label="热度" align="center" prop="hotkey"/>
      <!-- <el-table-column label="保底数量" align="center" prop="minNum" /> -->
      <el-table-column label="盒子类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type == 1">普通</el-tag>
          <el-tag type="danger" v-if="scope.row.type == 2">积分</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否全收" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type == 1">全收</el-tag>
          <el-tag type="danger" v-if="scope.row.type == 2">不开启</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column label="购买方式" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag :type="item == 1
      ? 'primary'
      : item == 2
        ? 'success'
        : item == 3
          ? 'info'
          : item == 4
            ? 'warning'
            : item == 5
              ? 'danger' : 'default'" v-for="item in scope.row.payType" :key="item">
            {{
              item == 1 ? '余额购买' : item == 2 ? '积分购买' : item == 3 ? 'M币抵扣' : item == 4 ? '流水购买' : item == 5 ? '现金购买' : ''
            }}
          </el-tag>
          <div v-if="scope.row.payType.indexOf('3') != -1">
            {{ scope.row.menKan }}
          </div>

          <!-- <svg-icon v-if="scope.row.payType == 1" icon-class="wechat" /> -->
          <!-- <svg-icon v-if="scope.row.payType == 2" icon-class="money" />
          <svg-icon v-if="scope.row.payType == 3" icon-class="logininfor" /> -->
        </template>
      </el-table-column>
      <el-table-column label="产生积分" align="center" prop="xgAll" sortable="custom">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.ifJf == 0">否</el-tag>
          <el-tag v-else>是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="产生流水" align="center" prop="xgAll" sortable="custom">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.ifLs == 0">否</el-tag>
          <el-tag v-else>是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="每日限购" align="center" prop="minNum" sortable="custom">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.minNum == 0">否</el-tag>
          <el-tag v-else>{{ scope.row.minNum }}</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="添加时间" align="center" prop="addtime" width="180">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.createDate, '{y}-{m}-{d} {hh}:{mm}:{ss}')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatetime" width="180">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.updateTime, '{y}-{m}-{d} {hh}:{mm}:{ss}')
            }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ scope.row.creator }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:wxs_box:edit']">修改
          </el-button>
          <el-button type="text" size="small" style="color:#67C23A" icon="el-icon-circle-plus-outline"
                     v-hasPermi="['system:wxs_goods:add']" @click="handleEditTable(scope.row)">添加商品
          </el-button>
          <el-button type="text" size="small" style="color:#909399" icon="el-icon-document-copy"
                     v-hasPermi="['system:wxs_box:copy']" @click="copyBox(scope.row.id)">复制盒子
          </el-button>

          <el-button size="mini" type="text" style="color:#F78989" icon="el-icon-delete"
                     @click="handleDelete(scope.row)" v-hasPermi="['system:wxs_box:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改盒子信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-button v-if="form.id == null" style="margin-bottom: 20px" type="primary" @click="importExcel">快捷导入
      </el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item  label="盒子名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入盒子名称"/>
        </el-form-item>
        <el-form-item  label="盒子封面图" prop="imgurl">
          <el-tooltip class="item" effect="dark" content="无限池封面图片（内外同图）
~" placement="top-start">
            <image-upload ref="upload" :limit="1" @input="handleFileUploadProgress" v-model="form.imgurl"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="盒子分类" prop="cId">
          <el-select v-model="form.cId" placeholder="请选择盒子分类">
            <el-option v-for="dict in infiniteCategories" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="是否上架">
          <el-radio-group v-model.number="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="排序值" prop="sort">
          <el-tooltip class="item" effect="dark" content="排序值越大越靠前哟~" placement="top-start">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" :max="9999"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="支付方式" prop="payType">
          <el-tooltip class="item" effect="dark" content="积分、流水、现金支付都只能单独设置，不能与其他方式一起使用~"
                      placement="top-start">
            <el-select v-model="form.payType" multiple placeholder="请选择支付方式">
              <el-option v-for="dict in dict.type.pay_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="审核显示" prop="status">
          <el-radio-group v-model.number="form.ifPublicShow">
            <el-radio :label="0">充值可见</el-radio>
            <el-radio :label="1">登录可见</el-radio>
            <el-radio :label="2">公开可见</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="盒子类型" prop="payType">
          <el-select v-model="form.type" placeholder="请选择盒子类型">
            <el-option v-for="dict in dict.type.box_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="阶段赏" prop="goodsInterval">
          <!-- <el-tooltip class="item" effect="dark" content="" placement="top-start"> -->
          <el-input v-model.number="form.goodsInterval"
                    placeholder="请输入阶段赏次数"/>
          <!-- </el-tooltip> -->
        </el-form-item>
        <el-form-item  label="产生积分" prop="ifJf">
          <el-switch v-model.number="form.ifJf" active-color="#13ce66" inactive-color="#F4F4F5" :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>

        <el-form-item  label="产生流水" prop="ifLs">
          <el-switch v-model.number="form.ifLs" active-color="#13ce66" inactive-color="#F4F4F5" :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item  label="每日限购" prop="minNum">
          <el-tooltip class="item" effect="dark" content="每日限购，0表示不限购，1表示限购1发，2表示限购2发，以此类推~"
                      placement="top-start">
            <el-input v-model="form.minNum" placeholder="请输入限购"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="盒子价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入盒子价格"/>
        </el-form-item>
        <el-form-item  label="抽成" prop="discount">
          <el-tooltip class="item" effect="dark" content="默认0.2即可，如需设置，请输入0.1-0.5之间的数字"
                      placement="top-start">
            <el-input v-model="form.discount" placeholder="请输入抽成"/>
          </el-tooltip>
        </el-form-item>
        <!-- <el-form-item label="热度" prop="hotkey">
          <el-input v-model="form.hotkey" placeholder="请输入热度" />
        </el-form-item> -->
        <el-form-item  label="奖池现有奖金" prop="menKan">
          {{ parseInt(this.form.menKan) + parseInt(this.jc) }}
          <el-tooltip class="item" effect="dark"
                      content="增加直接填入增加的金额，扣除则填入“-”和需要扣除的金额如-500则是扣除500，被扣除的奖池金额会纳入盈利金额"
                      placement="top-start">
            <el-input v-model="jc" placeholder="请输入奖池现有奖金"/>
          </el-tooltip>
        </el-form-item>
        <!-- <el-form-item label="保底数量" prop="minNum">
          <el-input v-model="form.minNum" placeholder="请输入保底数量" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 快捷导入 -->
    <el-dialog title="快捷导入" :visible.sync="dialogVisible" width="80%" center>
      <importform @func="update"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  addAwardPool
} from '@/api/wxs/box.js'
import {copyBox} from '@/api/yfs/box.js'
import {getToken} from '@/utils/auth'
import importform from './com_import.vue'
import myAffix from '@/components/affix.vue'
import {listWxsCategory} from "@/api/system/wxsCategory";

export default {
  dicts: ['box_status', 'box_type', 'pay_type'],
  name: 'Goods',
  components: {
    importform, myAffix
  },
  watch: {
    //监听支付方式
    'form.payType': function (val) {
      console.log(val)
      //判断数组是否有3
      if (val) {
        if (val.indexOf('3') != -1) {
          this.if_menkan = true
        } else {
          this.if_menkan = false
        }
      }
    }
  },
  data() {
    return {
      infiniteCategories: [],
      dialogVisible: false,
      if_menkan: false,
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/admin/uploadFile',
        // 上传的文件列表
        fileList: []
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盒子信息表格数据
      goodsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        isAsc: 'desc', // 排序，asc／desc
        orderByColumn: 'updateTime',
        pageNum: 1,
        pageSize: 10,
        cId: null,
        title: null,
        imgurl: null,
        sort: null,
        status: null,
        price: null,
        minNum: null,
        type: null,
        addtime: null,
        creator: null,
        createDate: null,
        sortType: null,
        ifPublicShow: null,
        ifAlchemy: 0
      },
      // 表单参数
      jc: 0,
      form: {},
      // 表单校验
      rules: {
        type: [{required: true, message: '请选择类型', trigger: 'change'}],
        cId: [{required: true, message: '分类id不能为空', trigger: 'blur'}],
        title: [
          {required: true, message: '盒子名称不能为空', trigger: 'blur'}
        ],
        imgurl: [
          {required: true, message: '盒子封面图不能为空', trigger: 'blur'}
        ],
        sort: [{required: true, message: '排序值不能为空', trigger: 'blur'}],
        status: [
          {
            required: true,
            message: '1上架 2 下架 3删除不能为空',
            trigger: 'blur'
          }
        ],
        price: [
          {required: true, message: '盒子价格不能为空', trigger: 'blur'}
        ],

        discount: [
          {required: true, message: '抽成不能为空', trigger: 'blur'}
          // { min: 0, max: 1, message: "抽成不能大于1", trigger: "blur" },
        ],

        type: [
          {required: true, message: '1普通 2积分不能为空', trigger: 'change'}
        ],
        addtime: [
          {required: true, message: '添加时间不能为空', trigger: 'blur'}
        ],
        updateTime: [
          {required: true, message: '修改时间不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getList()
    console.log(this.$store.getters)

    var _this = this
    document.onkeydown = function (e) {
      let key = window.event.keyCode
      if (key == 13) {
        _this.submitForm()
      }
    }
    const temp = {
      pageNum: 1,
      pageSize: 100,
      title: null,
      sort: null,
      status: 1,
    }
    listWxsCategory(temp).then(response => {
      this.infiniteCategories = response.rows.map(item => {
          return {
            label: item.id + '-' + item.title,
            value: Number(item.id)   //转int类型
          }

        }
      );
      console.log("this.infiniteCategories is", this.infiniteCategories)
    })
  },
  methods: {
    //复制盒子
    copyBox(data) {
      this.$modal.loading('正在复制盒子，请稍候...')
      copyBox({
        goodsId: data,
        type: 2
      }).then((res) => {
        this.getList()

        this.$modal.closeLoading()
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      })
    },

    update(value) {
      this.dialogVisible = false

      this.form = value
      if (this.form.payType) {
        this.form.payType = this.form.payType.split(',')
      }
      this.form.id = null
      this.form.goodsId = this.queryParams.goodsId
    },
    //快捷导入
    importExcel() {
      this.dialogVisible = true
      console.log('弹窗')
    },
    handleFileUploadProgress(e) {
      this.form.imgurl = e
    },
    /** 查询盒子信息列表 */
    async getList() {
      this.loading = true
      await listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows
        this.total = response.total
        this.loading = false
      })
      //转化支付方式数组
      this.goodsList.forEach((item, index) => {
        if (item.payType) {
          this.goodsList[index].payType =
            this.goodsList[index].payType.split(',')
        } else {
          item.payType = []
        }
      })
      console.log(this.goodsList)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        jc: 0,

        id: null,
        cId: null,
        title: null,
        imgurl: null,
        sort: null,
        status: 2,
        price: null,
        minNum: 0,
        type: null,
        addtime: null,
        updateTime: null,
        creator: null,
        createDate: null,
        payType: ['1'],
        sortType: 1,
        hotKey: null,
        disCount: null,
        menKan: null,
        ifPublicShow: 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加盒子信息'
    },

    //增减奖池
    addAwardPool(jc, goodsId) {
      if (jc == 0) {
        return
      }
      addAwardPool({
        goodsId: goodsId,
        jc: jc
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: jc > 0 ? '增加奖池成功' : '减少奖池成功',
            type: 'success'
          })
        }
      })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getGoods(id).then((response) => {
        this.form = response.data
        if (this.form.payType) {
          this.form.payType = this.form.payType.split(',')
        }
        this.form.type = '' + this.form.type
        this.open = true
        this.title = '修改盒子信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.payType = `${this.form.payType}`
          if (this.form.id != null) {
            console.log('this.form.cId is', this.form.cId )
            updateGoods(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
            console.log(this.form.jc, this.form.id)
            this.addAwardPool(this.jc, this.form.id)
          } else {
            this.form.creator = this.$store.getters.id
            addGoods(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除盒子信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGoods(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/goods/export',
        {
          ...this.queryParams
        },
        `goods_${new Date().getTime()}.xlsx`
      )
    },
    /** 添加商品 */
    handleEditTable(row) {
      const tableId = row.id
      const tableName = row.title
      //   const params = { pageNum: this.queryParams.pageNum };
      console.log(row)
      this.$tab.openPage(
        '添加[' + tableName + ']盒子商品',
        '/wxs/add_good/index/' + tableId
      )
    }
  }
}
</script>
